package cn.rongdao.jrkabao.ui.main.mainfragment.cashadvance;


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.http.request.event.CompulsoryDownLineEvent;
import com.mifengkong.frtools.inputmethod.FRView;
import com.mifengkong.frtools.util.FRCollection;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseViewPagerFragment;
import cn.rongdao.jrkabao.bean.cashadvance.HomeBean;
import cn.rongdao.jrkabao.bean.main.banner.BannerBean;
import cn.rongdao.jrkabao.bean.message.ReadPointBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.cashadvance.CashAdvanceModel;
import cn.rongdao.jrkabao.model.main.banner.BannerModel;
import cn.rongdao.jrkabao.model.message.ReadPointModel;
import cn.rongdao.jrkabao.ui.cashadvance.manager.LivenessManager;
import cn.rongdao.jrkabao.ui.main.MainActivity;
import cn.rongdao.jrkabao.ui.main.mainfragment.cashadvance.adapter.CashAdvanceAdapter;
import cn.rongdao.jrkabao.ui.main.mainfragment.cashadvance.ui.HomeIdentityUIComponent;
import cn.rongdao.jrkabao.ui.main.mainfragment.uicomponent.CashTitleBarUIComponent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.LoginUtil;

/**
 * 首页
 */
public class FragmentCashAdvance extends BaseViewPagerFragment {

    @BindView(R.id.fca_titlebar)
    CashTitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.fca_ptrContainer)
    RecyclerView recyclerView;

    private CashAdvanceAdapter cashAdvanceAdapter;
    private List<String> listData;
    private boolean isHaveMessage;
    private boolean isFirstGetData = true;
    private String imageUrl;
    private String link;
    private boolean isShowKaMao;  //是否需要弹窗无轮是那个
    private boolean isVisibleToUser = true; //界面是否隐藏
    private boolean isFirst = true;  //
    private boolean isOldInvitate; //是否是老用户邀请新用户的弹窗
    private View viewFooter;
    private LivenessManager livenessManager;

    @Override
    protected int layoutRes() {
        return R.layout.fragment_cash_advance;
    }

    @Override
    protected void onViewReallyCreated(View view) {
        super.onViewReallyCreated(view);
        if (listData == null) {
            listData = new ArrayList<>();
        }
        EventBus.getDefault().register(this);
        initPtrRecyclerView();
        initTitleBar();
        //获取banner数据
        getBanner();
    }

    private void initTitleBar() {
        titleBarUIComponent.setWhiteTitle(CommonUtil.getAppNameByApplicationId());
        titleBarUIComponent.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    }

    /**
     * 获取Banner数据
     */
    private void getBanner() {
        BannerModel.getInstance().execute("quxian_index_banner", new FRBaseObserver<List<BannerBean>>(this) {
            @Override
            protected void onBaseNext(List<BannerBean> data) {
                if (null != data && data.size() > 0) {
                    cashAdvanceAdapter.setBannerData(data);
                    //不能保证Banner的数据再其他的数据获取签获取所以这里也刷新一下
                    cashAdvanceAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 获取消息状态
     */
    private void readPointData() {
        ReadPointModel.getInstance().execute(new FRBaseObserver<ReadPointBean>(this) {
            @Override
            protected void onBaseNext(ReadPointBean data) {
                int message_switch = data.getMessage_switch();
                if (!CommonUtil.isStatusSuccess(message_switch)) {
                    titleBarUIComponent.setMessageVisible(false);
                    return;
                } else {
                    titleBarUIComponent.setMessageVisible(true);
                }
                isHaveMessage = CommonUtil.isStatusSuccess(data.getMessage_point());
                titleBarUIComponent.setIsHaveMessage(isHaveMessage);
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        listData.clear();
        //获取消息的状态
        readPointData();
        //获取列表数据
        CashAdvanceModel.getInstance().execute(new FRBaseObserver<HomeBean>(this, isFirstGetData ? "加载中，请稍后..." : "") {
            @Override
            protected void onBaseNext(HomeBean data) {
                if (data == null) {
                    return;
                }
                checkPopupWinow(data);

                HomeBean.RightTopCornerInfoBean right_top_corner_info = data.getRight_top_corner_info();
                initRightImag(right_top_corner_info);

                cashAdvanceAdapter.setHomeBean(data);
                //提款按钮
                HomeBean.CashButtonBean cash_button = data.getCash_button();
                if (cash_button != null) {
                    if (CommonUtil.isStatusSuccess(cash_button.getIs_show())) {
                        if (!listData.contains(CashAdvanceAdapter.HEAD)) {
                            listData.add(CashAdvanceAdapter.HEAD);
                        }
                    }
                }

                //navigation
                List<HomeBean.BlockListBean> index_model = data.getBlock_list();
                if (index_model != null && index_model.size() != 0) {
                    if (!listData.contains(CashAdvanceAdapter.NAVIGATION)) {
                        listData.add(CashAdvanceAdapter.NAVIGATION);
                    }
                }
                //Banner占位
                if (!listData.contains(CashAdvanceAdapter.BANNER)) {
                    listData.add(CashAdvanceAdapter.BANNER);
                }

                //身份认证
                HomeBean.UserInfoBean userInfoBean = data.getUser_info();
                if (null != userInfoBean && CommonUtil.isStatusSuccess(userInfoBean.getIs_show())
                        && !listData.contains(CashAdvanceAdapter.IDENTITY)) {
                    listData.add(CashAdvanceAdapter.IDENTITY);
                }

                //推荐的贷款
                List<HomeBean.LoanCommendBean> loan_commend = data.getLoan_commend();
                if (loan_commend != null && loan_commend.size() != 0) {
                    if (!listData.contains(CashAdvanceAdapter.LOAN)) {
                        listData.add(CashAdvanceAdapter.LOAN);
                    }
                }

                //其他的广告这个数据是有多个的做一下区分后缀加个position
                List<HomeBean.AdvModelBean> adv_model = data.getAdv_model();
                if (adv_model != null && adv_model.size() != 0) {
                    for (int i = 0; i < adv_model.size(); i++) {
                        if (!listData.contains(CashAdvanceAdapter.ADV + i)) {
                            listData.add(CashAdvanceAdapter.ADV + i);
                        }
                    }
                }
                cashAdvanceAdapter.setRefreshData(listData);
                viewFooter.setVisibility(View.VISIBLE);
            }
        });
        isFirstGetData = false;
    }

    private void checkPopupWinow(HomeBean data) {
        if (!FRString.isEmpty(FRSharedPreferences.getStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, ""))) {
            FRSharedPreferences.setStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, "");
            ((MainActivity) getActivity()).showDialogCheckUpdatePresenter();
        } else {
            if (null != data.getPop_up_info_new() && CommonUtil.isStatusSuccess(data.getPop_up_info_new().getIs_show())) {
                imageUrl = data.getPop_up_info_new().getImg_url();
                link = data.getPop_up_info_new().getLink_url();
                ((MainActivity) getActivity()).showKaMaoDialog(imageUrl, link);
            } else if (null != data.getPop_up_info_activity() && CommonUtil.isStatusSuccess(data.getPop_up_info_activity().getIs_show())) {
                //需要弹出首次活动的窗
                imageUrl = data.getPop_up_info_activity().getImg_url();
                link = data.getPop_up_info_activity().getLink_url();
                isOldInvitate = false;
                checkIsShowKaMao();
            } else {
                //老用户邀请新用户
                if (LoginUtil.isLogin()) {
                    if (null != data.getPop_up_info() && CommonUtil.isStatusSuccess(data.getPop_up_info().getIs_show())) {
                        imageUrl = data.getPop_up_info().getImg_url();
                        link = data.getPop_up_info().getLink_url();
                        isOldInvitate = true;
                        checkIsShowKaMao();
                    }
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        livenessManager.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        livenessManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void checkIsShowKaMao() {
        String phones;
        if (FRString.isEmpty(UserDao.getInstance().getPhone())) {
            return;
        }
        if (isOldInvitate) {
            phones = FRSharedPreferences.getStringNotClear(SPConstant.OLD_USERS_LOGIN_PHONE, "");
        } else {
            phones = FRSharedPreferences.getStringNotClear(SPConstant.ACTIVITY_USERS_LOGIN_PHONE, "");
        }
        List<String> phoneList = new ArrayList<>(Arrays.asList(phones.split(",")));
        if (FRString.isEmpty(phones)) {
            phoneList.clear();
        }
        if (!phoneList.contains(UserDao.getInstance().getPhone())) {
            isShowKaMao = true;
            if (isFirst && isVisibleToUser) {
                showKaMaoDialog(phoneList);
                isFirst = false;
            }
        } else {
            isShowKaMao = false;
        }
    }

    private void showKaMaoDialog(List<String> phoneList) {
        phoneList.add(UserDao.getInstance().getPhone());
        String newPhone = FRCollection.appendAsString(phoneList);

        if (isOldInvitate) {
            FRSharedPreferences.setStringNotClear(SPConstant.OLD_USERS_LOGIN_PHONE, newPhone);
        } else {
            FRSharedPreferences.setStringNotClear(SPConstant.ACTIVITY_USERS_LOGIN_PHONE, newPhone);
        }
        ((MainActivity) getActivity()).showKaMaoDialog(imageUrl, link);
        isShowKaMao = false;
    }


    //初始化titleBar右边图标
    private void initRightImag(HomeBean.RightTopCornerInfoBean rightBean) {
        String is_show = rightBean.getIs_show();
        String img_url = rightBean.getImg_url();
        String link_url = rightBean.getLink_url();
        if (CommonUtil.isStatusSuccess(is_show)) {
            titleBarUIComponent.setTitleRightVisible(true);
            titleBarUIComponent.setTitleRightImg(img_url);
            titleBarUIComponent.setRightImgOnClickLister(link_url);
        } else {
            titleBarUIComponent.setTitleRightVisible(false);
        }
    }

    /**
     * 初始化RecyclerView
     */
    private void initPtrRecyclerView() {
        livenessManager = new LivenessManager(this);
        viewFooter = FRView.inflateLayout(getContext(), R.layout.layout_cashadvance_footer);
        cashAdvanceAdapter = new CashAdvanceAdapter(getContext());
        RecyclerAdapterWithHF recyclerAdapterWithHF = new RecyclerAdapterWithHF(cashAdvanceAdapter);
        recyclerAdapterWithHF.addFooter(viewFooter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(recyclerAdapterWithHF);
        cashAdvanceAdapter.setOnHomeLivenessListener(new HomeIdentityUIComponent.OnHomeLivenessListener() {
            @Override
            public void onLiveness() {
                livenessManager.setInstitutionId("");
                livenessManager.startLivenessActiviity(titleBarUIComponent);
            }
        });
        livenessManager.initLivenessDialog(titleBarUIComponent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void compulsoryDownLineMessage(CompulsoryDownLineEvent compulsoryDownLineEvent) {
        LoginUtil.logout(getContext());
        readPointData();
    }

    @Override
    protected void onFragmentHiddenChanged(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            initData();
            if (isShowKaMao) {
                String phones;
                if (isOldInvitate) {
                    phones = FRSharedPreferences.getStringNotClear(SPConstant.OLD_USERS_LOGIN_PHONE, "");
                } else {
                    phones = FRSharedPreferences.getStringNotClear(SPConstant.ACTIVITY_USERS_LOGIN_PHONE, "");
                }
                List<String> phoneList = new ArrayList<>(Arrays.asList(phones.split(",")));
                showKaMaoDialog(phoneList);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isVisibleToUser){
            initData();
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
